import { patInfo } from "@/api/his";
import router from "@/router";
import { useUserStore } from "@/store/modules/user";
import { reactive, ref, onBeforeUnmount, watch, Ref, onBeforeMount } from 'vue';
import { closeLoading, delayTimeout, showLoading, resetTime } from ".";
import { IResult } from "./kiosk";
import { useScannerStore } from "@/store/modules/scanner"

import { useVariableStore } from "@/store/modules/variable";
import { $message } from "./tip";


/**tsx 插槽引用 */
export function showSlot(slots: Readonly<any>, slotName: string = "default") {
    return slots[slotName] ? slots[slotName]() : ""
}

// 后端分页
export function usePage(pageSize: number = 10) {
    return reactive({
        pageNum: 1,
        pageSize,
        total: 0,
        getParam() {
            return {
                pageNum: this.pageNum,
                pageSize: this.pageSize
            }
        },
        reset() {
            this.pageNum = 1
            this.total = 0
        }
    })
}

// 前端分页
export function useWebPage(pageSize: number = 10, data: any) {
    let pageConfig = reactive({
        // 总页数
        page:1,
        /** 当前页 */
        pageNum: 1,
        /** 每页多少条 */
        pageSize,
        /** 总条数 */
        total: 0,
        /** 显示的数据 */
        showData: [] as any[],
        /** 翻页 */
        turn() {
            let start = pageConfig.pageSize * (pageConfig.pageNum - 1)
            let end = pageConfig.pageSize * pageConfig.pageNum
            pageConfig.showData = data.slice(start, end)
        }
    })
    watch(() => data, (val) => {
        if (val && val.length) {
            pageConfig.total = val.length
            pageConfig.showData = data.slice(0, pageConfig.pageSize)
            pageConfig.page = Math.ceil(pageConfig.total / pageConfig.pageSize)
        }
    }, { immediate: true }) // 添加立即执行选项)

    return pageConfig
}

// 是否显示空状态
export function useError() {
    return reactive({
        show: false,
        handle(data: any) {
            if (!data || !data.length) {
                this.show = true
            } else {
                this.show = false
            }
        }
    })
}

/** 支付 - 微脉 */
export function usePay(outPatPay1: any, outPatCheck1: any, outPatCancel1: any) {

    let outPatPay: any=outPatPay1;
    let outPatCheck: any=outPatCheck1;
    let outPatCancel: any=outPatCancel1;
    const codeImg = ref("")
    const imgLoading = ref(true)
    const successVal = ref(null)
    let orderId = "";
    let end = false

    /** 发送支付请求 */
    async function getCodeData(...agm: any) {
        showLoading()
        const res = await outPatPay(...agm).finally(() => { closeLoading() })

        resetTime()
        codeImg.value = res.data?.smzf_qrcode!
        imgLoading.value = false
        orderId = res.data?.orderId!
        check()
    }

    const scannerStore = useScannerStore();

    const readCode = useReadCode("",async ()=>{
      scannerStore.setCode("");
      let readCodeValue=readCode.value.value;
      readCode.value.value="";
      if(!readCodeValue){
        return;
      }
      const variableStore = useVariableStore()
      variableStore.showLoading("正在支付中")
      // showLoading();
      const res = await outPatCheck({ sfdh: orderId,scan_barcode:readCodeValue }).finally(()=>{
          closeLoading();
      })
      if (res.code === 200) {
          //toStep4(res.data?.skdh!)
          if (res.data.print_json) {
              successVal.value = res.data?.skdh!
          } else {
              successVal.value = res.data?.skdh!
          }
          end=true;
          console.log("支付成功");
      }else{
         $message.error("支付失败")
      }
    });



    async function check() {
        if(codeImg.value && codeImg.value.startsWith("{")){
          let json=JSON.parse(codeImg.value);
          let smzf_enable=json.smzf_enable??true;
          if(smzf_enable===false){//扫码支付不存在 不定时获取支付状态
              return;
          }
        }
        const res = await outPatCheck({ sfdh: orderId })
        if (res.code === 200) {
            //toStep4(res.data?.skdh!)
            if (res.data.print_json) {
                successVal.value = res.data?.skdh!
            } else {
                successVal.value = res.data?.skdh!
            }

            console.log("支付成功");

        } else if (end) {
            // 解决bug
        } else {
            await delayTimeout(2000)
            check()
        }
    }

    let cancel_flag=0;
    async function handleCancel() {
        cancel_flag=1;
        showLoading()
        try {
            if (!orderId) {
                router.back()
                return
            }
            if(codeImg.value && codeImg.value.startsWith("{")){
              let json=JSON.parse(codeImg.value);
              let smzf_enable=json.smzf_enable??true;
              if(smzf_enable===false){//扫码支付不存在 不定时获取支付状态
                  if(!successVal.value){
                    await outPatCancel({ sfdh: orderId })
                    router.back()
                  }
                  return;
              }
            }

            const res = await outPatCheck({ sfdh: orderId })
            if (res.code === 501) {
                await outPatCancel({ sfdh: orderId })
                router.back()
            }
        } catch (error) {
            closeLoading()
        }
    }

    onBeforeUnmount(() => {
        end = true

        // 页面销毁时还未完成支付，则自动取消订单
        if (!successVal.value) {
            if(codeImg.value && codeImg.value.startsWith("{")){
              let json=JSON.parse(codeImg.value);
              let smzf_enable=json.smzf_enable??true;
              if(smzf_enable===false){//扫码支付不存在 不定时获取支付状态
                  outPatCancel({ sfdh: orderId })
                  return;
              }
            }
            showLoading()
            outPatCheck({ sfdh: orderId }).then((res:any)=>{
            if (res.code === 501) {
                if(cancel_flag==0){
                  outPatCancel({ sfdh: orderId })
                }
            }
            })
            .finally(() => {
                closeLoading();
            })
        }
    })

    return ref({
        codeImg,
        imgLoading,
        getCodeData,
        handleCancel,
        successVal,
        setFs(outPatPay1: any, outPatCheck1: any, outPatCancel1: any){
          outPatPay=outPatPay1;
          outPatCheck=outPatCheck1;
          outPatCancel=outPatCancel1;
        }
    })
}


/** 读卡 */
export function useReadCard(type: "sfz" | "sbk" | "dzsbk" | "jzk", run: (str?: string) => Promise<IResult>) {
    let end = false
    onBeforeMount(()=>{
      end=false;
    })
    onBeforeUnmount(() => {
        end = true
    })
    return ref({
        value: "",
        async run() {
            try {
                const res = await run();
                if(end){
                  return;
                }
                if (type === "dzsbk" && res.code !== 200) {
                    if (res.code > 500000) {

                        $message.error(res.message)
                    } else {
                        return
                    }
                }
                if (res.code === 200) {
                    this.value = await _readSuccess(res, type)
                    if (!this.value) {
                        await delayTimeout(1000)
                        this.run()
                    }
                } else if (end) {
                    // 退出递归
                } else {
                    await delayTimeout(1000)
                    this.run()
                }
            } catch (error) {
                if (type === "dzsbk") {
                    return
                }
                if (end) {
                    return;
                }
                console.log("错误");

                await delayTimeout(1000)
                this.run()
            }
        }
    })
}

/** 读取成功后执行 */
async function _readSuccess(res: any, type: any) {

    try {
        showLoading()
        const userStore = useUserStore()
        // 读卡成功
        const user = await patInfo({
            ...res.data,
            ldzzj_card_type: type
        })
        userStore.setCardInfo({ type, info: res })

        setTimeout(() => {
            if(!user.data!.JT_DH){
                /** 没有家庭电话 */
                userStore.setTempUser(user.data!)
                router.push("/tipMobile");
                return;
            }

            console.log("家庭地址：",user.data!.JT_DZ);

            if(!user.data!.JT_DZ){
                /** 没有家庭地址 */
                userStore.setTempUser(user.data!)
                router.push("/tipAddress");
                return;
            }
            //包含临时路由跳转
            userStore.setUser(user.data!);
        }, 500)

        return res.data.idCardNo
    } catch (error) {
        closeLoading()
        return ""
    }
}

/** 读条码 */
export function useReadCode(from?: string, fun?: (() => Promise<void>) | Function) {

    const scannerStore = useScannerStore();
    scannerStore.start();
    onBeforeUnmount(() => {
        scannerStore.end();
    })

    let value = ref("")

    watch(() => scannerStore.code, async (val) => {
        checkNum(val)
    })

    const checkNum = async (val: string) => {
        try {
            if (from) {
                value.value = await _readSuccess({
                    code: 200,
                    data: { cardIdCode: val },
                    message: ""
                }, "jzk")
            } else {
                value.value = val

                if (typeof fun !== "undefined") {
                    fun()
                }

            }
        } catch (error) {
            console.error("error:", error);

            closeLoading()
        }
    }

    return {
        value,
        async check() {
            if (this.value.value) {
                await checkNum(this.value.value)
            }
        }
    }
}
